<template>
  <div>
    <!-- 基础信息 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基础信息</span>
      </div>
      <div class="form-container">
        <!--添加规格信息-->
        <el-form ref="secondForm" :model="secondForm" :rules="rules" label-width="100px" class="demo-ruleForm" size="small">
          <div class="form-group">
            <!-- 宝贝规格 -->
            <div class="form-first">
              <div class="form-h">宝贝规格</div>
              <div class="form-first-value">
                <div v-for="(attr,index) in secondForm.specifications" :key="`attr${index}`" class="form-item">
                  <div class="form-title">
                    <span class="form-title-label">规格名：</span>
                    <el-autocomplete
                      v-model="attr.name"
                      :clearable="true"
                      :fetch-suggestions="querySearch"
                      class="inline-input"
                      size="small"
                      placeholder="请选择(可自定义输入)"
                      @input="changeInputValue(index, attr.name)"
                      @blur="changeValue(index, attr.name)"
                    />
                    <el-checkbox v-show="index === 0" v-model="attr.is_upload_url" @change="addImg">添加规格图片</el-checkbox>
                    <span class="delete" @click="toDelete(index, attr)">×</span>
                  </div>
                  <div style="display: flex;padding: 20px 0;">
                    <span class="form-title-label" style="padding-left: 10px">规格值：</span>
                    <ul class="form-list">
                      <li v-for="(item,index2) in attr.value_list" :key="`item${index2}`" class="form-list-item">
                        <el-autocomplete
                          v-model="item.value"
                          :fetch-suggestions="(queryString, cb) => {querySearchSpec(queryString, cb ,index)}"
                          class="inline-input"
                          style="margin-right:15px;margin-bottom:6px"
                          size="small"
                          placeholder="请选择(可自定义输入)"
                          @input="changeInputValueSpec(index, index2, item.value)"
                          @blur="changeValueSpec(index, index2, item.value)"
                        />
                        <i class="el-icon-close form-list-item-delete" @click="removeDomain(index, index2, item)"/>
                        <el-upload
                          v-if="attr.is_upload_url"
                          v-model="item.url"
                          :show-file-list="false"
                          :on-success="coverImgUpload"
                          :before-upload="beforeUserImgUpload"
                          :action="userHeadUploadApi"
                          :accept="'image/png,image/gif,image/jpg,image/jpeg'"
                          class="avatar-uploader form-list-item-img">
                          <img v-if="item.url" :src="item.url" class="el-icon-plus avatar-uploader-icon" @click="coverImgUploadNew(index, index2)">
                          <i v-else class="el-icon-plus avatar-uploader-icon" @click="coverImgUploadNew(index, index2)"/>
                        </el-upload>
                      </li>
                      <a v-if="attr.name" class="button-add" @click="addDomain(index)">添加规格值</a>
                    </ul>
                  </div>
                </div>
                <div v-show="secondForm.specifications.length < 3" class="form-btn-group"><button class="btn" type="button" name="" @click="addItem">添加规格项目</button></div>
              </div>
            </div>
            <!-- 规格明细 -->
            <div v-if="secondForm.specifications.length > 0" class="form-table">
              <div class="stock-title">规格明细</div>
              <el-table :data="secondForm.specification_details" :span-method="objectSpanMethod" border size="small">
                <el-table-column v-if="secondForm.specifications[0]&&secondForm.specifications[0].name" :label="secondForm.specifications[0]&&secondForm.specifications[0].name?secondForm.specifications[0].name:null" prop="first_class_value" width="140" align="center"/>
                <el-table-column v-if="secondForm.specifications[1]&&secondForm.specifications[1].name" :label="secondForm.specifications[1]&&secondForm.specifications[1].name?secondForm.specifications[1].name:null" prop="two_class_value" width="140" align="center"/>
                <el-table-column v-if="secondForm.specifications[2]&&secondForm.specifications[2].name" :label="secondForm.specifications[2]&&secondForm.specifications[2].name?secondForm.specifications[2].name:null" prop="three_class_value" width="140" align="center"/>
                <el-table-column prop="vip_price" label="会员价" width="140">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.vip_price" size="small" @blur="changeVipPrice(scope.row.vip_price, scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column v-if="company_id !== 10001" prop="cost_price" label="成本价" width="140">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.cost_price" size="small" @blur="changeCostPrice(scope.row.cost_price, scope.row)"/>
                  </template>
                </el-table-column>
                <el-table-column v-if="company_id !== 10001" prop="commission" label="佣金" width="140">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.commission" size="small" @blur="changeCommission(scope.row.commission)"/>
                  </template>
                </el-table-column>
                <el-table-column prop="inventory" label="库存" width="140">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.inventory" size="small" @blur="changeInventory(scope.row.inventory)"/>
                  </template>
                </el-table-column>
                <el-table-column :rules="[{ required: true, message: '请输入会员价格', trigger: 'blur' }]" prop="union_code" label="规格编码" width="140" >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.union_code" size="small"/>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="secondForm.specifications.length != 0" class="form-table" style="margin-top:15px">
              <div class="stock-title"/>
              <div style="display:flex">
                <div>
                  <span class="stock-title">统一会员价:</span>
                  <el-input v-model="vipPrice" size="small" style="width:140px" @blur="setVipPrice(vipPrice)"/>
                </div>
                <div v-permission="['ADMIN', 'COST_PRICE']">
                  <span class="stock-title" style="margin-left:10px">统一成本价:</span>
                  <el-input v-model="costPrice" size="small" style="width:140px" @blur="setCostPrice(costPrice)"/>
                </div>
                <div v-permission="['ADMIN', 'COST_PRICE']">
                  <span class="stock-title" style="margin-left:10px">统一库存:</span>
                  <el-input v-model="sameInventory" size="small" style="width:140px" @blur="setInventory(sameInventory)"/>
                </div>
              </div>
            </div>
          </div>
          <!--销售信息-->
          <div>
            <el-form-item label="会员价格：" prop="vip_price">
              <el-input :disabled="isVipPriceDisable" v-model="secondForm.vip_price" placeholder="请输入"/>
            </el-form-item>
            <el-form-item v-permission="['ADMIN', 'COST_PRICE']" label="成本价格：" prop="cost_price">
              <el-input :disabled="isCostPriceDisable" v-model="secondForm.cost_price" placeholder="请输入" />
            </el-form-item>
            <el-form-item v-permission="['ADMIN', 'SPECIAL_PRICE']" label="专柜价格：" prop="price">
              <el-input v-model="secondForm.price" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="库存：" prop="inventory">
              <el-input :disabled="isInventoryDisable" v-model="secondForm.inventory" placeholder="请输入"/>
            </el-form-item>
            <el-form-item label="宝贝编码：" prop="union_code">
              <el-input v-model="secondForm.union_code" placeholder="请输入"/>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  components: { },
  props: {
    specifications: {
      type: Array,
      required: true
    },
    form: {
      type: Object,
      required: true
    },
    percent: {
      type: Number,
      required: true
    },
    consumeProp: {
      type: Number,
      required: true
    },
    generalizeProp: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      rules: {
        vip_price: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        cost_price: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        share_save: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        commission: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        inventory: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      isVipPriceDisable: false,
      isCostPriceDisable: false,
      isInventoryDisable: false,
      secondForm: {
        specifications: [],
        specification_details: [],
        vip_price: '',
        cost_price: 0,
        price: 0,
        inventory: '',
        union_code: '',
        commission: 0,
        share_save: 0,
        consume: '',
        generalize: ''
      },
      specificationsList: [], // 一级规格
      oldSpecificationsList: [], // 一级规格
      firstForm: {},
      item: {}, // 一级规格选中项
      vipPrice: '', // 设置统一会员价
      costPrice: '', // 统一成本价
      sameInventory: '', // 统一库存
      is_upload_url: false, // 是否有图片
      coverImgUrl: '', // 规格图片
      index: 0,
      index2: 0,
      isAddImg: true,
      firstValue: null,
      secondValue: 0,
      OrderIndexArr: [],
      rowIndex: '-1',
      two_class_valueArr: [],
      indexList: {}, // 记录当前点击的List索引
      company_id: ''
    }
  },
  computed: {
    ...mapGetters([
      'userHeadUploadApi'
    ])
  },
  watch: {
    specifications(value) {
      // 规格选择
      const arr = value.map(item => {
        return {
          ...item,
          value: item.name,
          select: true,
          value_list: item.value.map(item => {
            return {
              ...item,
              value: item,
              select: true
            }
          })
        }
      })
      this.specificationsList = [...arr]
    },
    form(value) {
      // 回显值改为
      this.secondForm = value
      this.transformation(this.secondForm)
      this.secondForm.specifications = value.specifications ? value.specifications.map(item => {
        if (item.is_upload_url === 0) {
          return {
            ...item,
            consume: (item.commission * (this.consumeProp / 100)).toFixed(2),
            generalize: (item.commission * (this.generalizeProp / 100)).toFixed(2),
            is_upload_url: true
          }
        } else {
          return {
            ...item,
            consume: (item.commission * (this.consumeProp / 100)).toFixed(2),
            generalize: (item.commission * (this.generalizeProp / 100)).toFixed(2),
            is_upload_url: false
          }
        }
      }) : []
      if (value) {
        this.isVipPriceDisable = false
        this.isCostPriceDisable = false
        this.isInventoryDisable = false
      }
    }
  },
  created() {
    this.company_id = process.env.company_id
  },
  methods: {
    // 将规格值转换为table格式
    // 给父组件传递收取表单的值
    sendSecondMsg() {
      this.$refs['secondForm'].validate((valid) => {
        if (valid) {
          this.secondForm.result = true
        }
        this.secondForm.specifications = this.secondForm.specifications && this.secondForm.specifications.length > 0 ? this.secondForm.specifications.map(item => {
          if (item.is_upload_url) {
            return {
              ...item,
              is_upload_url: 0
            }
          } else {
            return {
              ...item,
              is_upload_url: 1
            }
          }
        }) : []
        this.$emit('msgEvent', this.secondForm)
      })
    },
    // 会员价和分享价监听，佣金总额改变
    changeValue3(vip_price, share_save) {
      const data = (vip_price * (this.percent / 100) - share_save).toFixed(2)
      this.$set(this.secondForm, 'commission', data)
    },
    addItem() {
      var obj = {
        name: '',
        key: this.generateUUID(),
        is_upload_url: false,
        value_list: []
      }
      if (this.secondForm.specifications.length >= 3) {
        return
      }
      // 只允许第一个规格添加图片，隐藏上传规格图片开关
      this.secondForm.specifications.push(obj)
      // 将规格值格式转换为表格格式
      this.transformation(this.secondForm)
    },
    toDelete: function(index, attr) {
      for (const list of this.specificationsList) {
        if (list.name === attr.name) {
          list.select = true
        }
      }
      this.secondForm.specifications.splice(index, 1)
      this.transformation(this.secondForm)
      // 重新计算会员价，成本价，库存
      if (this.secondForm.specifications.length > 0) {
        this.getMall()
      } else {
        this.isVipPriceDisable = false
        this.isCostPriceDisable = false
        this.isInventoryDisable = false
        this.secondForm.vip_price = ''
        this.secondForm.cost_price = ''
        this.secondForm.inventory = ''
      }
    },
    // 一级选择开始
    querySearch(queryString, cb) {
      var restaurants = this.specificationsList.filter(item => item.select)
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    changeValue(index, value) {
      const a = this.secondForm.specifications.map(item => item.name)
      const arr = []
      arr.push(value)
      const newArr = a.filter(item => arr.includes(item))
      if (newArr.length > 1) {
        this.$message({
          message: '已经添加了相同的规格值',
          type: 'error'
        })
        this.secondForm.specifications[index].name = ''
      }
      this.transformation(this.secondForm)
    },
    changeInputValue(index, value) {
      const a = this.secondForm.specifications.map(item => item.name)
      const b = this.specificationsList.map(item => item.name)
      const c = b.filter(item => a.includes(item))
      for (const list of this.specificationsList) {
        list.select = true
      }
      for (const item of c) {
        this.specificationsList[b.indexOf(item)].select = false
      }
      this.transformation(this.secondForm)
    },
    // 一级选择结束
    // 二级选择开始
    querySearchSpec(queryString, cb, index) {
      var value = this.secondForm.specifications[index].name
      this.specificationsList.map((item, index) => {
        if (item.value === value) {
          this.value_index = index
        }
      })
      var restaurants = this.specificationsList && this.specificationsList[this.value_index] ? this.specificationsList[this.value_index].value_list.filter(item => item.select) : []
      var results = queryString ? restaurants.filter(this.createFilterSpec(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilterSpec(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    changeValueSpec(index, index2, value) {
      const a = this.secondForm.specifications[index].value_list.map(item => item.value)
      const arr = []
      arr.push(value)
      const newArr = a.filter(item => arr.includes(item))
      if (newArr.length > 1) {
        this.$message({
          message: '已经添加了相同的规格值',
          type: 'error'
        })
        this.secondForm.specifications[index].value_list[index2].value = ''
      }
      // 二级选择框失去焦点时，禁用下面价格规格输入框
      this.isVipPriceDisable = true
      this.isCostPriceDisable = true
      this.isInventoryDisable = true
      this.transformation(this.secondForm)
    },
    changeInputValueSpec(index, index2, value) {
      const a = this.secondForm.specifications[index].value_list.map(item => item.value)
      if (this.value_index || this.value_index === 0) {
        const b = this.specificationsList[this.value_index].value_list.map(item => item.value)
        const c = b.filter(item => a.includes(item))
        for (const list of this.specificationsList[this.value_index].value_list) {
          list.select = true
        }
        for (const item of c) {
          this.specificationsList[this.value_index].value_list[b.indexOf(item)].select = false
        }
        this.transformation(this.secondForm)
      }
    },
    // 二级选择结束

    // 删除规格
    removeDomain(index, index2, item) {
      if (this.secondForm.specifications[index].value_list) {
        if (this.specificationsList.length > 0) {
          for (const list of this.specificationsList[index].value_list) {
            if (list.value === item.value) {
              list.select = true
            }
          }
        }
        this.secondForm.specifications[index].value_list.splice(index2, 1)
      } else {
        this.secondForm.specifications[index].value_list.splice(index2, 1)
      }
      this.transformation(this.secondForm)
    },
    addDomain(index) {
      if (this.secondForm.specifications.length < 0) {
        this.$message({
          message: '请选择(输入)规格值',
          type: 'error'
        })
        return
      }
      this.secondForm.specifications[index].value_list.push({
        value: '',
        url: '',
        key: this.generateUUID()
      })
      this.transformation(this.secondForm)
    },
    addImg(value) {
      this.secondForm.specifications[0].is_upload_url = value
    },
    // 图片上传
    coverImgUpload(res, file) {
      this.coverImgUrl = res
      this.secondForm.specifications[this.index].value_list[this.index2].url = this.coverImgUrl
      this.$forceUpdate()
    },
    coverImgUploadNew(index, index2) {
      this.index = index
      this.index2 = index2
    },
    // 上传图片之前校验
    beforeUserImgUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isLt3M
    },
    getMall() {
      this.$forceUpdate()
      this.secondForm.vip_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.vip_price }))
      this.secondForm.cost_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.cost_price }))
      this.secondForm.inventory = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.inventory }))
    },
    // 会员价格未输入失去焦点提醒
    changeVipPrice(value, detail) {
      if (value === '') {
        this.$message({
          message: '请输入',
          type: 'error'
        })
        return
      }
      this.updateSpecificationDetailCommission(detail)
      this.$forceUpdate()
      this.secondForm.vip_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.vip_price }))
    },
    changeCostPrice(value, detail) {
      if (value === '') {
        this.$message({
          message: '请输入',
          type: 'error'
        })
        return
      }
      this.updateSpecificationDetailCommission(detail)
      this.$forceUpdate()
      this.secondForm.cost_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.cost_price }))
    },
    changeCommission(value) {
      if (value === '') {
        this.$message({
          message: '请输入',
          type: 'error'
        })
        return
      }
      this.$forceUpdate()
    },
    changeInventory(value) {
      if (value === '') {
        this.$message({
          message: '请输入',
          type: 'error'
        })
        return
      }
      this.$forceUpdate()
      // 计算table表库存数据总和
      this.secondForm.inventory = this.secondForm.specification_details.map(o => o.inventory).reduce((acc, cur) => (parseFloat(cur) + acc), 0)
    },
    // 设置统一价格
    setVipPrice(value) {
      for (var i = 0; i < this.secondForm.specification_details.length; i++) {
        this.secondForm.specification_details[i]['vip_price'] = value
        this.updateSpecificationDetailCommission(this.secondForm.specification_details[i])
      }
      this.$forceUpdate()
      this.secondForm.vip_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.vip_price }))
    },
    setCostPrice(value) {
      for (var i = 0; i < this.secondForm.specification_details.length; i++) {
        this.secondForm.specification_details[i]['cost_price'] = value
        this.updateSpecificationDetailCommission(this.secondForm.specification_details[i])
      }
      this.$forceUpdate()
      this.secondForm.cost_price = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.cost_price }))
    },
    // 统一库存
    setInventory(value) {
      if (!value) {
        return
      }
      for (var i = 0; i < this.secondForm.specification_details.length; i++) {
        this.secondForm.specification_details[i]['inventory'] = value
      }
      this.$forceUpdate()
      this.secondForm.inventory = Math.min.apply(Math, this.secondForm.specification_details.map(function(o) { return o.inventory }))
    },
    merge() {
      const OrderObj = {}
      const two_class_valueObj = {}
      if (this.form.specification_details) {
        this.secondForm.specification_details = this.form.specification_details
      }
      this.secondForm.specification_details ? this.secondForm.specification_details.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.first_class_value]) {
          const nextItem = this.secondForm.specification_details[index + 1]
            ? this.secondForm.specification_details[index + 1].first_class_value
            : undefined
          const prevItem = this.secondForm.specification_details[index - 1].first_class_value
            ? this.secondForm.specification_details[index - 1].first_class_value
            : undefined
          if (element.first_class_value === nextItem) {
            OrderObj[element.first_class_value].push(index)
          } else if (element.first_class_value === prevItem) {
            OrderObj[element.first_class_value].push(index)
          }
        } else {
          OrderObj[element.first_class_value] = []
          OrderObj[element.first_class_value].push(index)
        }

        if (two_class_valueObj[element.two_class_value]) {
          const nextPro = this.secondForm.specification_details[index + 1]
            ? this.secondForm.specification_details[index + 1].two_class_value
            : undefined
          const prevPro = this.secondForm.specification_details[index - 1].two_class_value
            ? this.secondForm.specification_details[index - 1].two_class_value
            : undefined
          if (element.two_class_value === nextPro) {
            two_class_valueObj[element.two_class_value].push(index)
          } else if (element.two_class_value === prevPro) {
            two_class_valueObj[element.two_class_value].push(index)
          }
        } else {
          two_class_valueObj[element.two_class_value] = []
          two_class_valueObj[element.two_class_value].push(index)
        }
      }) : []

      // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
      for (const k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }

      for (const i in two_class_valueObj) {
        if (two_class_valueObj[i].length > 1) {
          this.handleData(two_class_valueObj[i])
        }
      }
    },
    // 新增的方法，处理当数组的长度大于2的时候
    handleData(data) {
      const temp = data
      let itemArr = []
      let itemArrNew = []
      // eslint-disable-next-line no-unused-vars
      let resArr = []
      if (data.length > 2) {
        for (let i = 0; i < data.length; i++) {
          if (data[i + 1]) {
            if (data[i + 1] - data[i] > 1) {
              itemArr = data.slice(0, i + 1)
              itemArrNew = temp.slice(i + 1, temp.length)
              break
            } else {
              resArr = data
            }
          }
        }
        if (itemArr.length > 0 || itemArrNew.length > 0) {
          this.two_class_valueArr.push(itemArr)
          this.two_class_valueArr.push(itemArrNew)
        } else {
          this.two_class_valueArr.push(data)
        }
      } else {
        this.two_class_valueArr.push(data)
      }
    },
    objectSpanMethod({ row, rowIndex, column, columnIndex }) {
      if (columnIndex === 0) {
        for (let i = 0; i < this.OrderIndexArr.length; i++) {
          const element = this.OrderIndexArr[i]
          for (let j = 0; j < element.length; j++) {
            const item = element[j]
            if (rowIndex === item) {
              if (j === 0) {
                return {
                  rowspan: element.length,
                  colspan: 1
                }
              } else if (j !== 0) {
                return {
                  rowspan: 0,
                  colspan: 0
                }
              }
            }
          }
        }
      }
      if (columnIndex === 1) {
        for (let j = 0; j < this.two_class_valueArr.length; j++) {
          const element = this.two_class_valueArr[j]
          for (let k = 0; k < element.length; k++) {
            const item = element[k]
            if (rowIndex === item) {
              if (k === 0) {
                return {
                  rowspan: element.length,
                  colspan: 1
                }
              } else if (k !== 0) {
                return {
                  rowspan: 0,
                  colspan: 0
                }
              }
            }
          }
        }
      }
    },
    transformation(info) {
      // 规格转换为规格明细具体实现
      // 规格重组，组装为多数组。重组为基础数据，例如
      // const arr = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z'], ['手机']]
      const array = []
      info && info.specifications ? info.specifications.map(res => {
        const list = []
        if (res.value_list.length > 0) {
          res.value_list.map(item => {
            list.push(item.key + '|' + item.value + '|' + item.url)
          })
          array.push(list)
        }
      }) : {}
      let recombination = []
      if (array.length === 1) {
        array[0].map(inf => {
          recombination.push([inf])
        })
      } else {
        // 数据二次重组,进行排列组合。数据如：[["a", 1, "x", "手机"], ["a", 1, "y", "手机"]]
        recombination = this.doExchange(array)
      }
      // 原生数据
      const oldList = info.specification_details
      // 和原数据进行对比，进行多条件过滤原数据，产生的新的数组
      const newList = []
      recombination && recombination.length > 0 ? recombination.map(item => {
        // 不改变原有的数据池
        let thisList = oldList
        // 数据形如 ["1-1|25ml|http://cdn.weiqiaoyun.com/mall/122/04518CC2E63DCEC7DA26C1FF58B28C1A.jpg", "2-1|麦香|null", "3-1|买1送2|null"]
        // 第一列数据进行筛选
        if (item.length > 0) {
          const firstItem = item[0].split('|')
          thisList = thisList && thisList.length > 0 ? thisList.filter(f => {
            if (f.first_class_id === firstItem[0]) {
              f.first_class_value = firstItem[1]
              f.first_class_url = firstItem[2]
            }
            return f.first_class_id === firstItem[0]
          }) : []
        }
        // 第二列数据筛选
        if (item.length > 1) {
          const twoItem = item[1].split('|')
          thisList = thisList && thisList.length > 0 ? thisList.filter(f => {
            if (f.two_class_id === twoItem[0]) {
              f.two_class_value = twoItem[1]
              f.two_class_url = twoItem[2]
            }
            return f.two_class_id === twoItem[0]
          }) : []
        }
        // 第三列数据筛选
        if (item.length > 2) {
          const threeItem = item[2].split('|')
          thisList = thisList && thisList.length > 0 ? thisList.filter(f => {
            if (f.three_class_id === threeItem[0]) {
              f.three_class_value = threeItem[1]
              f.three_class_url = threeItem[2]
            }
            return f.three_class_id === threeItem[0]
          }) : []
        }
        // 如果条件筛选后还存在值，则保留原有的数据，否则新建一条数据
        if (thisList.length > 0) {
          newList.push(thisList[0])
        } else {
          const object = this.newObject(item)
          newList.push(object)
        }
      }) : []
      this.secondForm.specification_details = newList
      // this.merge()
    },
    newObject(item) {
      const object = {
        first_class_id: item.length > 0 ? item[0].split('|')[0] : '',
        first_class_value: item.length > 0 ? item[0].split('|')[1] : '',
        first_class_url: item.length > 0 ? item[0].split('|')[2] : '',
        two_class_id: item.length > 1 ? item[1].split('|')[0] : '',
        two_class_value: item.length > 1 ? item[1].split('|')[1] : '',
        two_class_url: item.length > 1 ? item[1].split('|')[2] : '',
        three_class_id: item.length > 2 ? item[2].split('|')[0] : '',
        three_class_value: item.length > 2 ? item[2].split('|')[1] : '',
        three_class_url: item.length > 2 ? item[2].split('|')[2] : '',
        vip_price: '',
        cost_price: '',
        inventory: '',
        union_code: '',
        commission: ''
      }
      return object
    },
    doExchange(arr) {
      const len = arr.length
      // 当数组大于等于2个的时候
      if (len >= 2) {
        // 第一个数组的长度
        const len1 = arr[0].length
        // 第二个数组的长度
        const len2 = arr[1].length
        // 2个数组产生的组合数
        const lenBoth = len1 * len2
        //  申明一个新数组
        const items = new Array(lenBoth)
        // 申明新数组的索引
        let index = 0
        for (let i = 0; i < len1; i++) {
          for (let j = 0; j < len2; j++) {
            if (arr[0][i] instanceof Array) {
              items[index] = arr[0][i].concat(arr[1][j])
            } else {
              items[index] = [arr[0][i]].concat(arr[1][j])
            }
            index++
          }
        }
        const newArr = new Array(len - 1)
        for (let i = 2; i < arr.length; i++) {
          newArr[i - 1] = arr[i]
        }
        newArr[0] = items
        return this.doExchange(newArr)
      } else {
        return arr[0]
      }
    },
    // 生成唯一id
    generateUUID() {
      var d = new Date().getTime()
      if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now() // use high-precision timer if available
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
      })
      return uuid
    },
    // 修改某一个规格详细的佣金值
    updateSpecificationDetailCommission(detail) {
      if (detail) {
        const cost_price = detail.cost_price ? detail.cost_price : 0
        const vip_price = detail.vip_price ? detail.vip_price : 0
        detail.commission = (vip_price - cost_price) >= 0 ? (0.6 * (vip_price - cost_price)).toFixed(2) : 0
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-container {
  width: 90%;
}
.box-card {
  margin-bottom: 10px;
}
.el-card__body {
  padding: 20px 20px 0 20px!important;
}
.form-container-parameter {
  background: #f3f3f3;
  padding: 20px 20px 0 0;
}

button,input{
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    outline: none;
    height: 32px;
    border-radius: 4px;
    font-size: 14px;
    color: #606266;
  }
  .btn{
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    color: #333;
    vertical-align: middle;
    cursor: pointer;
    background-color: #fff;
    border: 1px solid #ddd;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
  }
  .btn.active, .btn:active, .btn:focus, .btn:hover {
    text-decoration: none;
    color: #333;
    background-color: #fcfcfc;
    border-color: #ccc;
  }
  /*table*/
  table{
    border:0;
  }
  table.table-sku {
    width: 100%;
    background-color: #fff;
    text-align: left;
    font-size: 14px;
    color: #606266;
  }
  table {
    border-collapse: collapse;
    border-spacing: 0;
  }
  table.table-sku td {
    border: 1px solid #e5e5e5;
    padding: 8px;
  }
  table.table-sku td input{
    padding: 10px;
    border: 1px solid #ccc;
    width: 110px;
  }
  /**/
  .form-title{
    background: #f8f8f8;
    padding: 10px;
    position: relative;
  }
  .form-title .label{
    color:#999;
  }
  .form-title-label {
    color: #606266;
    font-size: 14px;
    width: 70px;
  }
  .form-first {
    display: flex;
  }
  .form-first-value {
    border: 1px solid #EBEEF5;
    border-radius: 4px;
    padding: 10px;
    width: 100%;
  }
  .form-title .delete{
    width: 20px;
    height: 20px;
    line-height: 15px;
    border: 1px solid #ccc;
    border-radius: 50%;
    position: absolute;
    right: 15px;
    top: 50%;
    margin-top: -10px;
    text-align: center;
    color: #fff;
    background: #ccc;
    cursor: pointer;
  }
  .form-title input{
    background: #fff;
    border: 1px solid #ccc;
    padding: 10px;
  }
  ul, li{
    padding: 0!important;
    margin: 0!important;
    list-style: none!important;
  }
  ul {
    padding-inline-start: 5px!important;
  }
  .form-list{
    margin-top:0;
    box-sizing: border-box;
    width: calc(100% - 70px);
    display: flex;
    flex-wrap: wrap;
    .form-list-item {
      position: relative;
      margin-right: 10px;
    }
    .form-list-item-delete {
      background: #ccc;
      color: #fff;
      position: absolute;
      border-radius: 50%;
      padding: 3px;
      font-size: 12px;
      top: -8px;
      right: 8px;
      cursor: pointer;
    }
    .form-list-item-img {
      margin-bottom: 10px;
    }
  }
  .form-list li{
    display: inline-block;
    margin-top:10px;
  }
  .spec-item{
    width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .form-list,.form-title{
    text-align:left;
  }
  .form-list  input{
    background: #fff;
    margin-right: 15px;
    border: 1px solid #ccc;
    padding: 10px;
  }
  .form-group{
    margin-bottom: 20px;
  }
  .form-table{
    margin-top: 30px;
    display: flex;
  }
  .form-btn-group{
    background: #f8f8f8;
    padding: 10px;
  }
  .stock-title,.form-h{
    width: 100px;
    height: 32px;
    line-height: 32px;
    font-size: 14px;
    color: #606266;
    text-align: right;
    padding: 0 12px 0 0;
    font-weight: 500;
  }
  .button-add {
    color: #409EFF;
    font-size: 14px;
    box-sizing: border-box;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 1px dashed #C0C4CC;
  }
  .avatar {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
</style>
